package com.linkage.bookshop.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.linkage.bookshop.model.Book;
import com.linkage.bookshop.model.Comment;
import com.linkage.bookshop.repository.BookRepository;
import com.linkage.bookshop.repository.CommentRepository;
import com.linkage.bookshop.repository.UserRepository;
import com.linkage.bookshop.service.inter.CommentService;

@Service("commentService")
public class CommentServiceImpl implements CommentService {
	@Autowired
	private CommentRepository commentRepository;
	@Autowired
	private UserRepository userRepository;

	@Autowired
	private BookRepository bookRepository;

	@Override
	public boolean deleteComment(int commentId) {
		// TODO Auto-generated method stub
		Comment comment = new Comment();
		comment = commentRepository.selectByCommentId(commentId);
		if (comment == null) {
			return false;
		}
		commentRepository.delete(commentId);
		return true;

	}

	@Override
	public List<Comment> listBookComments(int bookId) {
		// TODO Auto-generated method stub
		List<Comment> comments = commentRepository.findByBookId(bookId);

		return comments;
	}

	@Override
	public boolean insert(String username, int bookId, String content, int grade) {
		// TODO Auto-generated method stub
		Book book = new Book();
		book = commentRepository.selectBookById(bookId);
		if (book == null) {
			return false;
		}

		if (content.equals(null)) {
			return false;
		}
		int userId = userRepository.selectUserId(username);
		Comment comment = new Comment();
		comment.setUserId(userId);
		comment.setBookId(bookId);
		comment.setContent(content);
		comment.setGrade(grade);
		comment.setTime(new Date());
		comment.setVisibleFlag(false);
		commentRepository.insert(comment);
		return true;
	}

	@Override
	public List<Comment> listBookComments(int bookId, int pageNum) {
		int offset = 0;
		int rows = 8;
		offset = offset + 8 * (pageNum - 1);
		return this.commentRepository.selectBookComment(bookId, offset, rows);
	}

}
